﻿
//
// 版权所有 (c) 2021-2023 JR
//
// 特此免费授予获得本软件的任何人以处理本软件的权利，但须遵守以下条件：在所有副本或重要部分的软件中必须包括上述版权声明和本许可声明。
//
// 软件按“原样”提供，不提供任何形式的明示或暗示的保证，包括但不限于对适销性、适用性和非侵权的保证。
// 在任何情况下，作者或版权持有人均不对任何索赔、损害或其他责任负责，无论是因合同、侵权或其他方式引起的，与软件或其使用或其他交易有关。

namespace EMC.VISITOR.Core;

/// <summary>
/// SqlSugar相关常量
/// </summary>
public class SqlSugarConst
{
    /// <summary>
    /// 默认数据库标识（默认租户）
    /// </summary>
    public const string MainConfigId = "1300000000001";

    /// <summary>
    /// 日志数据库标识
    /// </summary>
    public const string LogConfigId = "1300000000002";

    /// <summary>
    /// MES数据库标识
    /// </summary>
    public const string MESConfigId = "1300000000003";

    /// <summary>
    /// WMS数据库标识
    /// </summary>
    public const string WMSConfigId = "1300000000004";

    /// <summary>
    /// 默认数据库标识（默认租户）- 被迁移的目标库
    /// </summary>
    public const string MainConfigIdTransfer = "1300000000001_1";
    /// <summary>
    ///MES数据库标识- 被迁移的目标库
    /// </summary>
    public const string MESConfigIdTransfer = "1300000000003_1";
    /// <summary>
    ///WMS数据库标识- 被迁移的目标库
    /// </summary>
    public const string WMSConfigIdTransfer = "1300000000004_1";
    /// <summary>
    /// 默认表主键
    /// </summary>
    public const string PrimaryKey = "Id";


    public static DbConnectionOptions options = App.GetOptions<DbConnectionOptions>();


    public static string GetDataBaseConfigId(Type entityType)
    {
        string configId = string.Empty;
        if (entityType == null)
            return configId;
        if (!entityType.GetCustomAttribute<BusinessVSAttribute>().IsNullOrEmpty())
        {
            configId = SqlSugarConst.MESConfigId;
        }
        else if (!entityType.GetCustomAttribute<BusinessWmsAttribute>().IsNullOrEmpty())
        {
            configId = SqlSugarConst.WMSConfigId;
        }
        else if (!entityType.GetCustomAttribute<LogTableAttribute>().IsNullOrEmpty())
        {
            configId = SqlSugarConst.LogConfigId;
        }
        else if (!entityType.GetCustomAttribute<TenantAttribute>().IsNullOrEmpty())
        {
            configId = SqlSugarConst.MainConfigId;
        }
        else
        {
            configId = SqlSugarConst.MainConfigId;
        }
        //var configId = attr == null ? SqlSugarConst.MainConfigId : attr.configId.ToString();
        //entityType.GetCustomAttribute
        return configId;
    }

    public static string GetDdataBaseFullName(Type entityType)
    {
        string resultName = string.Empty;
        string tableName = entityType.Name;
        var configId = GetDataBaseConfigId(entityType);
        var attributeSugarTable = entityType.GetCustomAttribute<SugarTable>();
        if (!attributeSugarTable.TableName.IsNullOrEmpty())
            tableName = attributeSugarTable.TableName;

        var db = options.ConnectionConfigs.FirstOrDefault(r => r.ConfigId == configId);

        bool enableUnderLine = db.DbSettings.EnableUnderLine;
        var tablePrefix = db.TableSettings.TablePrefix; //表前缀
        var tableSuffix = db.TableSettings.TableSuffix; //表后缀

        if (db != null && db.DbType == SqlSugar.DbType.SqlServer)
            resultName = $"{db.DbName}.{tablePrefix}{tableName}{tableSuffix}";
        //if (db != null && db.DbType == SqlSugar.DbType.PostgreSQL)
        //    return $"{db.DbName}.{entityType.Name}";
        else
            resultName = tablePrefix + tableName + tableSuffix;

        return resultName;
    }

    public static string GetDataBaseConfigId(string tableName)
    {
        var type = GetTypeByTableName(tableName);
        return GetDataBaseConfigId(type);
    }
    public static string GetDdataBaseFullName(string tableName)
    {
        var type = GetTypeByTableName(tableName);
        return GetDdataBaseFullName(type);
    }
    public static Type GetTypeByTableName(string tableName)
    {
        var entityType = App.EffectiveTypes.Where(u =>
        (u.Name.Contains(tableName) || (u.GetCustomAttribute<SugarTable>() != null && !u.GetCustomAttribute<SugarTable>().TableName.IsNullOrEmpty() && u.GetCustomAttribute<SugarTable>().TableName.Contains(tableName))) &&
        !u.IsInterface &&
        !u.IsAbstract &&
        u.IsClass &&
        u.IsDefined(typeof(SugarTable), false))
    .FirstOrDefault();

        if (entityType == null)
            return default(Type);

        return entityType;
    }
    public static string GetModelName(string tableName)
    {
        var entityType = GetTypeByTableName(tableName);
        return entityType.Name;
    }

    public static string GetTableName(DbConnectionConfig config, string modelName)
    {
        bool enableUnderLine = config.DbSettings.EnableUnderLine;
        var tablePrefix = config.TableSettings.TablePrefix; //表前缀
        var tableSuffix = config.TableSettings.TableSuffix; //表后缀
        return (tablePrefix + (enableUnderLine ? UtilMethods.ToUnderLine(modelName) : modelName) + tableSuffix);
    }
}